#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

static char pwm_path[100];

static int pwm_config(const char *attr, const char *val)
{
	char *file_path[100];

	int len, fd;

	sprintf(file_path, "%s/%s", path_pwm, attr,)
	fd = fopen(file_path, O_WRONLY);
	if (fd < 0) {
		printf("%s open error\n", file_path);
		return fd;
	}

	len = strlen(val);
	if (write(fd, val, len) != len) {
		printf("%s write error\n", file_path);
		close(fd);
		return -1;
	}

	close(fd);
	return 0;
}

staic int export_pwm(char *path)
{
	int fd;

	fd = open(path, O_WRONLY);
	if (fd < 0) {
		printf("pwm export file open error\n");
		return -1;
	}

	if (write(fd, "0", 1) != 1) {
		printf("pwm export failed\n");
		close(fd);
		return -1;
	}

	close(fd);
	return 0;
}


int main(int argc, char *argv[])
{
	if (argc != 4) {
		printf("usage: %s <id> <period> <duty>\n", argv[0]);
		eixt(-1);
	}
	
	sprintf(pwm_file, "/sys/class/pwm/pwmchip%s/pwm0", argv[1]);
	if (access(pwm_path, F_OK)) {
		char *export_path=[100];
		sprintf(export_path, "%s/%s", pwm_file, "export");
		if (export_pwm(export_path)) {
			eixt(-1);
		}
	}

	
	if (pwm_config("period", argv[2])) {
		eixt(-1);
	}

	if (pwm_config("duty", argv[3])) {
		eixt(-1);
	}

	pwm_config("enable", "1");

	exit(0);


}
